<script setup lang="ts">
import { ref, onMounted } from 'vue';
import ProblemGenerator from './components/ProblemGenerator.vue';
import ProblemScanner from './components/ProblemScanner.vue';
import ResultAnalysis from './components/ResultAnalysis.vue';
import InstructionsDialog from './components/InstructionsDialog.vue';
import { useQuasar } from 'quasar';
import { useUserStore } from './stores/user';
import { useRouter } from 'vue-router';

const $q = useQuasar();
const userStore = useUserStore();
const router = useRouter();

// 当前显示的页面
const activeTab = ref('generator');

// 添加反馈对话框的显示状态
const showFeedbackDialog = ref(false);
const feedbackContent = ref('');
const feedbackEmail = ref('');

// 添加使用说明对话框的显示状态
const showInstructionsDialog = ref(false);

// 检查登录状态
onMounted(async () => {
  const token = localStorage.getItem('token');
  const userData = localStorage.getItem('user');
  
  if (token && userData) {
    try {
      // 恢复用户状态
      await userStore.restoreUserState(JSON.parse(userData));
      // 如果当前在登录页面，则跳转到首页
      if (router.currentRoute.value.path === '/login') {
        router.push('/');
      }
    } catch (error) {
      // 如果恢复状态失败，清除本地存储
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      if (router.currentRoute.value.path !== '/login') {
        router.push('/login');
      }
    }
  } else if (router.currentRoute.value.path !== '/login') {
    router.push('/login');
  }
});

// 提交反馈
const submitFeedback = async () => {
  if (!feedbackContent.value) {
    $q.notify({
      message: '请输入反馈内容',
      color: 'warning'
    });
    return;
  }
  
  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/feedback`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        content: feedbackContent.value,
        email: feedbackEmail.value
      })
    });

    const data = await response.json();
    
    if (data.success) {
      $q.notify({
        message: '感谢您的反馈！',
        color: 'positive'
      });
      
      // 清空表单并关闭对话框
      feedbackContent.value = '';
      feedbackEmail.value = '';
      showFeedbackDialog.value = false;
    } else {
      throw new Error(data.message || '提交失败');
    }
  } catch (error: any) {
    console.error('提交反馈失败:', error);
    $q.notify({
      message: `提交失败: ${error.message || '未知错误'}`,
      color: 'negative'
    });
  }
};
</script>

<template>
  <div>
    <router-view></router-view>

    <!-- 浮动按钮 -->
    <div class="floating-buttons">
      <q-btn
        round
        color="primary"
        icon="help"
        @click="showInstructionsDialog = true"
      />
      <q-btn
        round
        color="secondary"
        icon="feedback"
        @click="showFeedbackDialog = true"
      />
    </div>

    <!-- 反馈对话框 -->
    <q-dialog v-model="showFeedbackDialog">
      <q-card style="min-width: 350px">
        <q-card-section>
          <div class="text-h6">反馈意见</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-input
            v-model="feedbackContent"
            type="textarea"
            label="请输入您的反馈意见"
            :rules="[val => !!val || '请输入反馈内容']"
            autogrow
          />
          <q-input
            v-model="feedbackEmail"
            type="email"
            label="联系邮箱（选填）"
            class="q-mt-md"
          />
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" v-close-popup />
          <q-btn flat label="提交" @click="submitFeedback" />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <!-- 使用说明对话框 -->
    <InstructionsDialog v-model="showInstructionsDialog" />
  </div>
</template>

<style>
body {
  font-family: "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: 0;
  padding: 0;
  height: 100%;
}

.floating-buttons {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.floating-buttons .q-btn {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
</style>
